CTM = new Ext.Application({
	name: "ChingaTown Mobile",
	launch : function () {
		Ext.regModel("Badges", {fields: ["name", "description", "image", "image2", "url"]});

		CTM.badges_store = new Ext.data.Store({
			model : "Badges"
		});
		
		$.ajax({
			url: "lib/proxy.php",
			dataType: "html",
			success: function(data) {
				$(data).find("div#badgeSelection").find("li").each(function(index,element) {
					CTM.badges_store.add({
						id:				$(element).attr("data-idBadge"), 
						name:			$(element).find("strong").html(), 
						description:	$(element).find("em").html(), 
						image:			$(element).find("img").attr("src"), 
						major_url:		$(data).find("li#badge-" + $(element).attr("data-idBadge") + " > h5 > a").attr("href"),
						major_name: 	$(data).find("li#badge-" + $(element).attr("data-idBadge") + " > h5 > a").html(),
						url:			$(element).attr("rel")
					});
				});
			}
		});
		
		
		CTM.badge_toolbar = new Ext.Toolbar({
			items : [{
				text : "Back",
				ui : "Back",
				handler : function () {
					CTM.main_panel.setActiveItem("badges_panel", {type : "slide", direction : "right"});
				}
			}]
		});
		
		CTM.badge_panel = new Ext.Panel({
			id: "badge_panel",
			layout : "fit",
			tpl : [
				'<div style="width:100%;text-align:center; float: left;"><img src="{image}"/></div>',
				'<div style="width:100%;text-align:left; float: left; padding:20px;"><p>{description}</p></div>'
			],
			dockedItems : [CTM.badge_toolbar]
		});
		
		CTM.badges_toolbar = new Ext.Toolbar({
			title : 'ChingaTown Mobile'
		});
		
		CTM.badges_list = new Ext.List({
			id : "badges_list",
			store : CTM.badges_store,
			itemTpl : '<img src="{image}" width="40" height="40"/> {name} <a href="{major_url}">{major_name}</a> {id}',
			disableSelection : true,
			listeners : {
				itemtap : function(view, index, item, e) {
					var badge = CTM.badges_store.getAt(index);
					CTM.badge_toolbar.setTitle(badge.get("name"));
					CTM.badge_panel.update(badge.data);
					CTM.main_panel.setActiveItem("badge_panel");
				}
			}
		});
		
		CTM.badges_panel = new Ext.Panel({
			id : "badges_panel",
			layout : "fit",
			items : [CTM.badges_list],
			dockedItems : [CTM.badges_toolbar]
		});
		
		CTM.main_panel = new Ext.Panel({
			id: "main_panel",
			fullscreen : true,
			layout : "card",
			cardSwitchAnimation : "slide",
			items : [CTM.badges_panel, CTM.badge_panel]
		});
	}
});